﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Nancy;
using System.IO;
using System.Configuration;
using Nancy.ModelBinding;
using PlatWL.Services.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using PlatWL.Models;

namespace PlatWL.Modules.Other
{
    public class FileModule : SimpleModule
    {
        public FileModule(FileManage service)
            : base("file")
        {
            //重定向文件路径
            Get["/{id}"] = p =>
            {
                string filename = service.GetFileUrl(p.id);
                return Response.AsRedirect(filename);
            };
            Get["/thum/{id}/{width?0}/{height?0}"] = p => //缩略图，默认原图
            {
                string filename = service.GetFileUrl(p.id, p.width, p.height);
                return Response.AsRedirect(filename);
            };
            Post["/addfile"] = p =>
            {
                var files = (JArray)JsonConvert.DeserializeObject(Request.Form["P1"]);
                service.AddFile(ref msg, files);
                return Response.AsJson(msg);
            };
            Get["/download/{id}"] = p =>
            {
                string filename = HttpContext.Current.Server.MapPath("/Export/");
                filename = filename + p.id;

                return Response.AsFile(filename, "application/excel");
            };
            //上传文件到文件服务器
            Post["/uploadfile"] = p =>
            {
                try
                {
                    if (Request.Files.Count() > 0)
                    {
                        JArray j = new JArray();
                        List<int> flist = new List<int>();
                        foreach (HttpFile file in Request.Files)
                        {
                            if (file.ContentType.Contains("image"))
                            {
                                string[] temp = file.Name.Split('.');
                                string filename = Guid.NewGuid() + "." + temp[temp.Length - 1].ToLower();
                                string URL = System.Configuration.ConfigurationManager.AppSettings["fileServer"].ToString() + "/document/fileupload";
                                string md5 = Tools.Common.HttpPostFile(URL, filename, file).Replace("\"", "");

                                //保存到文件表

                                JObject jo = new JObject();
                                jo.Add(new JProperty("filename", file.Name));
                                jo.Add(new JProperty("md5", md5));
                                jo.Add(new JProperty("filesize", file.Value.Length.ToString()));

                                j.Add(jo);
                            }
                        }

                        service.AddFile(ref msg, j);
                    }else
                    {
                        msg.error = "请选择文件";
                    }
                }
                catch (Exception)
                {
                    msg.error = "上传图片失败";
                }
                return Response.AsJson(msg);
            };
            
            //转码通知
            Post["/zmnotice"] = p =>
            {

                try
                {
                    if (Request.Body != null)
                    {
                        Stream stream = Request.Body;
                        StreamReader reader = new StreamReader(stream);
                        string text = reader.ReadToEnd();
                        reader.Close();
                        //string header = Request.Headers.Authorization;
                        //CommonClass.WriteLog("1","zmdone",text);
                        //CommonClass.WriteLog("1", "zmdone", header);

                        //判断转码是否成功
                        // {
                        //"Message": "{\"jobId\":\"334d5f2680b5461fa84a50d13f69a9d3\",\"Type\":\"Transcode\",\"state\":\"Success\",\"UserData\":\"8d71c478d755ae444f686f037d22ff82\",\"userData\":\"8d71c478d755ae444f686f037d22ff82\",\"type\":\"Transcode\",\"State\":\"Success\",\"JobId\":\"334d5f2680b5461fa84a50d13f69a9d3\"}",
                        //"MessageId": "4ED2B0D9B07840F-1-15E13E7B766-200000012",
                        //"MessageMD5": "40297CB77471C82259796AC404BE06F0",
                        //"PublishTime": "1503572506470",
                        //"Subscriber": "1774223038365237",
                        //"SubscriptionName": "zhuanmatongzhi",
                        //"TopicName": "zmtongzhi",
                        //"TopicOwner": "1774223038365237"}
                        //
                        Services.Tools.Common.WriteLog(text);

                        if (!string.IsNullOrEmpty(text))
                        {
                            JObject jo = JObject.Parse(text);
                            JObject message = JObject.Parse(jo["Message"].ToString());
                            string Type = message["Type"].ToString();
                            string state = message["state"].ToString();
                            string UserData = message["UserData"].ToString();
                            if (Type == "Transcode" && state == "Success")
                            {
                                string outFlag = "";
                                string md5 = UserData;
                                if (UserData.IndexOf("|") > -1)
                                {
                                    md5 = UserData.Split('|')[0];
                                    outFlag = UserData.Split('|')[1];
                                }

                                ////直接转码，处理转码状态
                                //if (outFlag == "" || outFlag == "1")
                                //{
                                //     new VideoManage().ZM_Video_1(md5);
                                //}
                                //else if (outFlag == "2") //通过服务器视频截取
                                //{
                                //    new VideoManage().ZM_Video_2(md5);
                                //}

                                return Response.AsText("HTTP/1.1 204 No Content");
                            }
                        }

                        //HTTP/1.1 204 No Content
                        //正常处理通知消息，返回 204；
                        //请求签名验证不通过，返回 403；
                        //其他任何错误，返回 500。
                    }
                }
                catch(Exception ex) { Services.Tools.Common.WriteLog(ex.Message); }
                return Response.AsText("HTTP/1.1 500 No Content");
            };

        }
    }
}